/// @tags:
#include <cstdio>
#include <iostream>

using namespace std;

namespace BlueQuantum {

typedef long long LL;

inline int main() {
  int t;
  cin >> t;
  for (int i = 1; i <= t; ++i) {
    LL a, b, c, p;
    cin >> p >> a >> b >> c;
    if (p % a == 0 || p % b == 0 || p % c == 0) cout << "0\n";
    else
      cout << min(a - p % a, min(b - p % b, c - p % c)) << '\n';
  }
  return 0;
}

}  // namespace BlueQuantum

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("/tmp/CodeTmp/testdata.in", "r", stdin);
  freopen("/tmp/CodeTmp/testdata.out", "w", stdout);
#else
  freopen("A Three swimmers.in", "r", stdin);
  freopen("A Three swimmers.out", "w", stdout);
#endif
#endif

  ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  return BlueQuantum::main();
}
